import { actionBuilder } from '../utils';
import { appActions } from '../app';
import numModel from '../num';

export const Namespace = 'count';

type State = {
    count: number;
};

type Reducer = {
    ADD_COUNT: State;
};

type Effect = {
    addCountAsync: any;
};

type Action = {
    type: string;
    payload: number;
};

const model = {
    namespace: Namespace,
    state: {
        count: 0,
    },
    reducers: {
        ADD_COUNT(state: State, action: Action) {
            return {
                ...state,
                count: state.count + action.payload,
            };
        },
    },
    effects: {
        *addCountAsync({ payload }: Action, { put, delay, select }: any) {
            yield put(appActions.SET_LOADING(true));
            yield delay(1000);
            yield put(countActions.ADD_COUNT(payload));

            // yield put({
            //     type: 'ADD_COUNT', # namespace没有时会自动添加
            //     payload,
            // }); # 相当于这样，好处是不用维护type了
            yield put(appActions.SET_LOADING(false));
            const count = yield select((state) => state['num.1']);
            if (count) {
                yield put.resolve(appActions.REMOVE_MODEL('num.1'));
            }
        },
    },
    subscriptions: {
        init({ dispatch }, onError) {
            // 动态添加一个model
            dispatch({
                type: 'app/ADD_MODEL',
                payload: {
                    ...numModel,
                    namespace: `num.1`,
                },
            });
        },
    },
};

export const countActions = actionBuilder<Reducer & Effect>(model);
// action creator (payload?any)=>{type:string;payload?:any}
// subscriptions key没约束，自定义名称，执行后可返回一个取消订阅函数
//  app.model执行时添加subscriptions中的函数，app.start() 的时候遍历执行一次，返回取消订阅函数， app.unmodel(namespace) 执行时，遍历执行返回的取消订阅函数
export default model;
